import React, { useState, useEffect, useCallback, useRef } from 'react';
import type { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import { Modal, Tree, Input, FormInstance, message, Empty, Button } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { history } from 'umi';
import TreeControlled from '@/components/ProTree/components';
import {
  getByScope,
  ucOrganizationDeleteId,
  ucOrganizationPage,
} from '@/services/deptControl';
import { formatTreeData } from '@/services/common';
const { confirm } = Modal;
import styles from './index.less';
import Const from '@/utils/Const';

const DeptIndex: React.FC = () => {
  const [selectedKeys, setSelectedKeys] = useState<any[]>([]);
  const [checkedKeys, setcheckedKeys] = useState([]);
  const [checkedTitles, setcheckedTitles] = useState([]);
  // 受控的ProForm
  const ref = useRef<FormInstance>();
  // 组织架构
  const [departmentTree, setDepartmentTree] = useState<Array<any>>();
  // 组织架构选中
  const [departmentSelected, setDepartmentSelected] = useState('');
  // 组织架构选中option
  const [selectedOption, setSelectedOption] = useState('');

  const [treeModalVisible, settreeModalVisible] = useState<boolean | undefined>(
    false,
  );
  // 是否展示创建跟节点按钮
  const [isShow, setIsShow] = useState(false);

  const TableCustomDeploy = {
    componentName: 'customTable',
  };

  const user = JSON.parse(localStorage.getItem('user') as string) || {};
  // 用户权限
  // 1: admin，2：普通管理员，3:普通用户
  const userType = user?.type;

  useEffect(() => {
    getDepartmentTreeByRole();
  }, []);

  // 初始化组织树
  const getDepartmentTreeByRole = async () => {
    // 根据接口获取值
    const orgType = userType === 1 ? 0 : 1;
    let res = await getByScope({ orgType });
    if (res?.data) {
      // 写入值
      setDepartmentTree(formatTreeData(res?.data));

      // 写入默认选择的id
      setDepartmentSelected(res?.data[0]?.id);
      setSelectedOption(res?.data[0]?.option);

      // 写入默认选择的key

      setSelectedKeys([res?.data[0]?.key + '']);
    }
    ref.current?.submit();
    const isShow = userType === 1 && !res.data;
    setIsShow(isShow);
  };

  // 删除
  const deleteOrganization = useCallback((id) => {
    confirm({
      title: '删除提示信息',
      icon: <ExclamationCircleOutlined />,
      content: '该操作将删除当前数据，确定删除吗？',
      async onOk() {
        const result = await ucOrganizationDeleteId(id);
        if (result.code === 200) {
          message.success('数据删除成功');
          ref.current?.submit();
          getDepartmentTreeByRole();
        }
      },
    });
  }, []);

  // 编辑
  const editOrganization = (record: any, pageType: string) => {
    history.push({
      pathname: '/features/dept/deptEdit',
      state: {
        id: record.id,
        isFirst: record.isFirst,
        parentId: record.parentId,
        pageType,
      },
    });
  };

  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    const columns: ProColumns[] = [
      {
        dataIndex: 'index',
        title: '序号',
        valueType: 'indexBorder',
      },
      {
        title: '机构名称',
        dataIndex: 'name',
        valueType: 'text',
        order: 1,
      },
      {
        title: '简称',
        dataIndex: 'shortName',
        valueType: 'text',
        order: 3,
      },
      {
        title: '类型',
        dataIndex: 'type',
        valueType: 'text',
        hideInSearch: true,
        valueEnum: {
          1: { text: '公司' },
          2: { text: '部门' },
        },
      },
      {
        title: '人数',
        dataIndex: 'peopleNum',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '负责人',
        dataIndex: 'personInCharge',
        valueType: 'text',
        order: 4,
        renderFormItem: (_, { defaultRender }) => {
          return (
            <Input
              value={
                checkedTitles?.length > 0 ? checkedTitles.join('，') : '请选择'
              }
              onClick={() => {
                settreeModalVisible(true);
              }}
            />
          );
        },
      },
      {
        title: '电话',
        dataIndex: 'phone',
        valueType: 'select',
        order: 2,
        valueEnum: {
          0: { text: '正常', status: 'Success' },
          1: { text: '停用', status: 'Error' },
          2: { text: '锁定', status: 'Default' },
        },
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => [
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => editOrganization(record, 'add')}
          >
            新增
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => editOrganization(record, 'check')}
          >
            详情
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => editOrganization(record, 'edit')}
          >
            编辑
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => deleteOrganization(record.id)}
          >
            删除
          </a>,
        ],
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          'selectedRows: ',
          selectedRows,
        );
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    return {
      columns,
      request: async (params = {}, sort, filter) => {
        if (departmentSelected && selectedOption !== '0') {
          const filterParams = { ...params, id: departmentSelected };
          let res = await ucOrganizationPage(filterParams);
          let resData = Const.dealResDataSwitch(res);
          return Promise.resolve(resData);
        } else {
          return null;
        }
      },
      formRef: ref,
      rowSelection: {
        type: 'checkbox',
        ...rowSelection,
      },
      pagination: {
        pageSize: 5,
      },
      rowKey: 'id',
      // toolBarRender: () => [
      //   // <Button icon={<FilterOutlined />}>查询</Button>,
      //   <Button
      //     icon={<PlusOutlined />}
      //     onClick={() => {
      //       history.push('/features/dept/deptEdit');
      //     }}
      //   >
      //     新增机构
      //   </Button>,
      //   <Button
      //     icon={<PlusOutlined />}
      //     onClick={() => {
      //       history.push('/features/dept/nodeEdit');
      //     }}
      //   >
      //     新增节点
      //   </Button>,
      //   <Button
      //     onClick={() => {
      //       history.push({
      //         pathname: '/features/dept/auth',
      //         state: {
      //           type: 'index',
      //         },
      //       });
      //     }}
      //   >
      //     组织批量授权
      //   </Button>,
      // ],
    };
  };
  const onChangeSelect = (keys: any[], { selected, node }: any) => {
    setSelectedKeys(keys);
    setDepartmentSelected(node.id);
    setSelectedOption(node.option);
    ref.current?.submit();
    // let nodeObj = lodash.clone(node.props || {});
    // nodeObj.key = nodeObj.key ? nodeObj.key : nodeObj.value;
    // setDept(nodeObj.dataRef ? nodeObj.dataRef : nodeObj);
    // if (selected) {
    //   setSelectedKeys(keys);
    // }
  };
  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };

  return (
    <div>
      <div className={`${styles.container} ${styles.deptIndex}`}>
        {departmentTree && (
          <TreeControlled
            showLine
            className={styles.tree}
            selectable
            data={departmentTree}
            selectedKeys={selectedKeys}
            setSelectedKeys={onChangeSelect}
            title="组织机构"
          />
        )}
        {
          // 没有跟节点且是管理员可以新建跟节点
          isShow && (
            <Empty description="没有发现可用组织，需要创建新的根节点吗？">
              <Button
                type="primary"
                onClick={() => editOrganization({}, 'addNode')}
              >
                创建根节点
              </Button>
            </Empty>
          )
        }
        <ProTable {...jsonOption}></ProTable>
      </div>
      <Modal
        title="组织架构"
        visible={treeModalVisible}
        onOk={() => {
          settreeModalVisible(false);
        }}
        onCancel={() => {
          settreeModalVisible(false);
        }}
      >
        <Tree
          style={{ maxHeight: '50vh', overflowY: 'auto' }}
          checkable
          autoExpandParent={true}
          checkedKeys={checkedKeys}
          onCheck={(checkedKeysValue: any, checkedRow: any) => {
            let rowsByTitle = checkedRow.checkedNodes.map(
              (item: any) => item.title,
            );
            setcheckedTitles(rowsByTitle);
            setcheckedKeys(checkedKeysValue);
          }}
          treeData={departmentTree}
        />
      </Modal>
    </div>
  );
};

export default DeptIndex;
